import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import PdfViewer from '@/components/PdfViewer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';

const PdfPreview = () => {
  console.log('=== PdfPreview 组件开始渲染 ===');
  
  const location = useLocation();
  const [fileInfo, setFileInfo] = useState(null);

  console.log('当前路由位置:', location);
  console.log('路由状态数据:', location.state);

  useEffect(() => {
    console.log('PdfPreview useEffect 触发');
    console.log('location.state:', location.state);
    
    // 从路由状态中获取文件信息
    if (location.state && location.state.fileList && location.state.fileList.length > 0) {
      console.log('找到文件列表，设置第一个文件信息');
      console.log('文件列表:', location.state.fileList);
      console.log('选择的文件:', location.state.fileList[0]);
      setFileInfo(location.state.fileList[0]);
    } else {
      console.warn('未找到有效的文件信息');
      console.warn('location.state:', location.state);
    }
  }, [location.state]);

  console.log('当前文件信息状态:', fileInfo);

  if (!fileInfo) {
    console.log('渲染文件信息缺失页面');
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-96">
          <CardHeader>
            <CardTitle className="text-red-600">文件信息缺失</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600">
              无法获取PDF文件信息，请重新访问预览链接。
            </p>
            <div className="mt-4 text-xs text-gray-400">
              <p>调试信息:</p>
              <p>location.state: {JSON.stringify(location.state)}</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  console.log('渲染PDF预览组件');
  console.log('传递给PdfViewer的参数:', {
    fileUrl: fileInfo.fileUrl,
    fileName: fileInfo.fileName
  });

  return (
    <PdfViewer 
      fileUrl={fileInfo.fileUrl} 
      fileName={fileInfo.fileName} 
    />
  );
};

export default PdfPreview;
